//
//  ShortVideoListViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/2/27.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "ShortVideoListViewController.h"
#import "videoListModel.h"
#import "ShortVideoLogic.h"
#import "VideoListItemCollectionViewCell.h"
#import "VideoPlayViewController.h"
//cell宽度
#define ShortVideoCellWidth KScreenWidth/2-2
#define SDCycleHeight 120

@interface ShortVideoListViewController ()<videoListLogicDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@end

@implementation ShortVideoListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _logic = [ShortVideoLogic new];
    _logic.type = self.type;
    _logic.delegagte = self;
    [self setupUI];
}


#pragma mark ————— 初始化页面 —————
-(void)setupUI{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView.collectionViewLayout = layout;
    layout.minimumLineSpacing = 1;//设置最小行间距
    layout.minimumInteritemSpacing = 1;//item间距(最小值)
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置section的编距
    self.collectionView.backgroundColor = CViewBgColor;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([VideoListItemCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([VideoListItemCollectionViewCell class])];
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
}

#pragma mark ————— 下拉刷新 —————
-(void)headerRereshing{
    _logic.page = 1;
    [_logic loadData];
    [self removeNoDataImage];
    
}

#pragma mark ————— 上拉刷新 —————
-(void)footerRereshing{
    _logic.page+=1;
    [_logic loadData];
    [self removeNoDataImage];
}

#pragma mark ————— 数据拉取完成 渲染页面 —————
-(void)requestDataCompleted{
    [self.collectionView.mj_footer endRefreshing];
    [self.collectionView.mj_header endRefreshing];
    
    [UIView performWithoutAnimation:^{
        [self.collectionView reloadData];
    }];
    
}

#pragma mark ————— collection代理方法 —————
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(KIOSBASE && _logic.dataArray.count !=0)
    {
        return 1;
    }
    else
    {
        return _logic.dataArray.count;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoListItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([VideoListItemCollectionViewCell class]) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.00];
    cell.model = _logic.dataArray[indexPath.row];
    return cell;
}

//-(void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [_logic loadData];
//}

//*******重写的时候需要走一句话
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectIndexPath = indexPath;
    videoListModel *model = _logic.dataArray[indexPath.row];
    //检查视频是否扣费
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"short_video_api" A:@"get_video"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:curUser.id forKey:@"uid"];
    [param setObject:StringFromInt(model.id) forKey:@"video_id"];
    [[HUDHelper sharedInstance] syncStopLoading];
    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self goVideoViewWithModel:model];
    } failure:^(NSString *error,NSInteger errCode) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
        
        if(errCode == 10020)
        {
            NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"此视频为付费视频，需要消耗%@%@，是否购买"),model.coin,KCOIN_NAME];
            QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
                
            }]];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"购买")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
                [self buyVideoViewWithModel:model];
            }]];
            
            [alert showWithAnimated:YES];
            
            return;
        }
 
    } hasCache:NO];
    
    return;
    
    if(model.status == 2 && model.type == 0)
    {
        
        NSString *buyTip = [NSString stringWithFormat:ASLocalizedString(@"此视频为付费视频，需要消耗%@%@，是否购买"),model.coin,KCOIN_NAME];
        QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:ASLocalizedString(@"提示")message:buyTip preferredStyle:QMUIAlertControllerStyleAlert];
        [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"取消")style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
            
        }]];
        
        [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"购买")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
            [self buyVideoViewWithModel:model];
        }]];
        [alert showWithAnimated:YES];
        return;
    }
    else
    {
        [self goVideoViewWithModel:model];
    }
}

-(void)buyVideoViewWithModel:(videoListModel *)model
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"short_video_api" A:@"buy_video"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [[HUDHelper sharedInstance] syncLoading];
    [param setObject:StringFromInt(model.id) forKey:@"video_id"];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [self goVideoViewWithModel:model];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
}

-(void)goVideoViewWithModel:(videoListModel *)model
{
    VideoPlayViewController *vc = [[VideoPlayViewController alloc] init];
    vc.model = model;
    vc.videoList = _logic.dataArray;
    vc.currentIndex = self.selectIndexPath.row;
    NSLog(@"vc.currentIndex %ld",(long)vc.currentIndex);
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0 )
    {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    int width = KScreenWidth/2-0.5;
    return CGSizeMake(width,width*5/3);
}

////  返回头视图
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    //如果是头视图
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
//        //添加头视图的内容
//        [self addContent];
//        //头视图添加view
//        [header addSubview:self.cycleScrollView];
//        return header;
//    }
//    //如果底部视图
//    //    if([kind isEqualToString:UICollectionElementKindSectionFooter]){
//    //
//    //    }
//    return nil;
//}
/*
 *  补充头部内容
 */
//-(void)addContent
//{
//    //    NSArray *imagesURLStrings = @[];
//    //
//    //    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KScreenWidth, SDCycleHeight) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
//    //    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
//    //    cycleScrollView.currentPageDotColor = MainColor;
//    //    cycleScrollView.imageURLStringsGroup = imagesURLStrings;
//    //
//    //
//    //    self.cycleScrollView = cycleScrollView;
//    //    self.cycleScrollView=cycleScrollView;
//}

#pragma mark ————— 转场动画起始View —————
//-(UIView *)targetTransitionView{
//    NSIndexPath * indexPath = [self.collectionView currentIndexPath];
//    PersonListCollectionViewCell *cell =(PersonListCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    return cell.imgView;
//}

//-(BOOL)isNeedTransition{
//    return YES;
//}


-(void)naviBtnClick:(UIButton *)btn{
    DLog(ASLocalizedString(@"点击了筛选按钮"));
}

-(void)viewWillAppear:(BOOL)animated
{
    [_logic loadData];
    self.navigationController.navigationBar.hidden = YES;
    self.collectionView.frame = CGRectMake(0, 0, KScreenWidth, SCREEN_HEIGHT - TabBarHeight - kTopHeight);
    
}




#pragma mark -  上下滑动隐藏/显示导航栏

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
